import { Toast } from "antd-mobile";
import { reqLogin } from "../../http/api";

// 1.初始值
const initState = {
    // 1.1初始化user
    user: {
        phone: '',
        password: ""
    },
    // 2.1用户信息初始值--info: {}--- 2.7 刷新页面的时候，看本地存储是否有值，没有就是值，没有就是{}
    info: sessionStorage.getItem('info') ? JSON.parse(sessionStorage.getItem('info')) : {}
}

// types
const types = {
    // 1.2 user的type
    LOGIN_CHANGE_USER: 'LOGIN_CHANGE_USER',
    // 2.2 info的type
    LOGIN_CHANGE_INFO: "LOGIN_CHANGE_INFO"
}
// reducer
export const loginReducer = (state = initState, action) => {
    switch (action.type) {
        // 1.3 user的action
        case types.LOGIN_CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
            break;
        // 2.3 修改info
        case types.LOGIN_CHANGE_INFO:
            return {
                ...state,
                info: action.info
            }
            break;
        default:
            return state
    }
}
// actions
export const actions = {
    // 1.4修改user
    changeUser: (key, value) => ({ type: types.LOGIN_CHANGE_USER, key, value }),
    //    1.4 修改info
    changeInfo: info => {
        // 2.6 本地存储存info ---但可能是退出登录---所以要做判断
        if (info.token) {
            sessionStorage.setItem("info", JSON.stringify(info))
        } else {
            sessionStorage.removeItem('info')
        }

        return { type: types.LOGIN_CHANGE_INFO, info }
    },

    // 1.7 登录的逻辑
    loginAction: (push) => {
        return (dispatch, getState) => {
            // 取出user---在login仓库里取出user
            let { user } = getState().login
            //1.8 发请求
            reqLogin(user).then(res => {
                if (res.data.code === 200) {
                    //1.9 弹成功
                    Toast.success(res.data.msg)
                    //1.10 存用户信息-----2.用户信息初始值
                    dispatch(actions.changeInfo(res.data.list))
                    //1.11 跳转页面
                    // this.props.history.push('/index/home')
                    push('/index/home')
                }
            })
        }
    },  

}


//1.5 导出数据
export const getUser = state => state.login.user
// 2.5 导出info
export const getInfo = state => state.login.info